package com.yxym.homework;

public class Homework02 {
    public static void main(String[] args) {
        MoneySell moneySell1 = new MoneySell();
        Thread thread1 = new Thread(moneySell1);
        Thread thread2 = new Thread(moneySell1);
        thread1.setName("m");
        thread2.setName("n");
        thread1.start();
        thread2.start();
    }
}

class MoneySell implements Runnable{//涉及多线程
    private int TotalMoney = 10000;
    private boolean loop = true;

    public void sell(){
        synchronized (this){//获取一把锁线程争夺这把锁，那个线程争夺到this对象锁，
            // 就执行synchronized 代码块，执行完成后，就会释放this的对象锁
            //如果争夺不到这个锁就阻塞（block）
            if( TotalMoney <= 1000){
                System.out.println("余额不足，无法取款");
                loop = false;
                return;
            }else {
                TotalMoney-=1000;
                System.out.println(Thread.currentThread().getName() +
                        "余额为=" + TotalMoney + "\t");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        while (loop){
            sell();//同步方法
        }
    }
}